package com.forlove.app.qselect.login.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.forlove.app.R;
import com.forlove.app.common.base.ui.BaseActivity;
import com.forlove.app.common.utils.CipherUtils;
import com.forlove.app.common.utils.CryptAES;
import com.forlove.app.common.utils.LogUtil;
import com.forlove.app.common.utils.MyTimeUtils;
import com.forlove.app.common.utils.StringUtils;
import com.forlove.app.common.widget.PinEntryEditText;
import com.forlove.app.manager.NetworkManager;
import com.forlove.app.manager.UserManager;
import com.forlove.app.qselect.login.entity.LoginEntity;
import com.forlove.app.qselect.login.entity.UserEntity;
import com.forlove.app.qselect.login.presenter.ValidateCodePresenter;
import com.forlove.app.qselect.login.view.ValidateCodeView;
import com.forlove.app.qselect.login.widget.ErrorMessageView;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;

/**
 * 手机验证码验证页面
 * Created by yjl on 2017/10/30.
 */

public class ValidateCodeActivity extends BaseActivity<ValidateCodePresenter>
        implements View.OnClickListener, ValidateCodeView {

    @BindView(R.id.text_hint)
    TextView hintTextView;

    @BindView(R.id.edittext_input_code)
    PinEntryEditText pinEntryEditText;

    @BindView(R.id.view_error_message)
    ErrorMessageView view_error_message;//错误信息提示

    @BindView(R.id.text_send_phone_again)
    TextView text_send_phone_again;

    @BindView(R.id.bt_identify_nextstep)
    TextView bt_identify_nextstep;

    private int second = 60;
    private String phoneCode;//手机号
    private String identifyCode;//验证码
    private LoginEntity loginEntity;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 99999) {
                second--;
                text_send_phone_again.setText(second + "秒后重发");
                text_send_phone_again.setOnClickListener(null);
                if (second <= 0) {
                    second = 60;
                    text_send_phone_again.setText("重新发送");
                    text_send_phone_again.setOnClickListener(ValidateCodeActivity.this);
                } else {
                    handler.sendEmptyMessageDelayed(99999, 1000);
                }
            }
        }
    };

    @Override
    public int getLayoutId() {
        return R.layout.activity_validate_code;
    }

    @Override
    public void initView() {
        if (presenter == null) {
            presenter = new ValidateCodePresenter(this);
        }
        pinEntryEditText.setHintTextView(hintTextView);
        bt_identify_nextstep.setOnClickListener(this);
        text_send_phone_again.setOnClickListener(this);
        initEditeStatus();
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            phoneCode = bundle.getString("phone");
            if (TextUtils.isEmpty(phoneCode)) {
                this.finish();
            }
        }
        text_send_phone_again.setVisibility(View.VISIBLE);
        text_send_phone_again.setText(second + "秒后重发");
        handler.sendEmptyMessageDelayed(99999, 1000);
    }

    @Override
    protected void onResume() {
        super.onResume();
//        StatusBarCompat.compat(this, Color.parseColor("#ffffff"));
    }


    private void initEditeStatus() {
        pinEntryEditText.setOnPinEnteredListener(new PinEntryEditText.OnPinEnteredListener() {
            @Override
            public void onPinEntered(CharSequence str) {
                if (!TextUtils.isEmpty(str)) {
                    bt_identify_nextstep.setBackground(getResources().getDrawable(R.drawable.bt_register_nextstep_selector));
                } else {
                    bt_identify_nextstep.setBackground(getResources().getDrawable(R.drawable.bg_register_nextstep_corner_sel));
                }
            }
        });

    }

    private void requestIdentifyCode() {
        identifyCode = pinEntryEditText.getText().toString();
        LogUtil.e("yjl", "code:" + identifyCode);
        if (TextUtils.isEmpty(identifyCode)
                || identifyCode.length() < 6) {
            view_error_message.setVisibility(View.VISIBLE);
            view_error_message.setError("请输入验证码!");
            return;
        }
        Map<String, String> param = new HashMap<>();
        param.put("mobile", phoneCode);
        param.put("msgCode", identifyCode);
        presenter.loadIdentifyCode(param);
    }

    /**
     * 遗忘，重置密码
     */
    private void requestSendMsgAgain() {

        if (TextUtils.isEmpty(phoneCode)) {
            view_error_message.setError("请输入手机号码");
            view_error_message.setVisibility(View.VISIBLE);
            return;
        } else if (!StringUtils.isMobile(phoneCode)) {
            view_error_message.setError("请输入正确的手机号码");
            view_error_message.setVisibility(View.VISIBLE);
            return;
        }
        UserEntity userEntity = UserManager.getUesrInfo(this);
        if (userEntity == null) {
            return;
        }
        loginEntity = new LoginEntity();
        loginEntity.mobile = userEntity.userMobile;
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(loginEntity.mobile);
        String time = MyTimeUtils.formatDate(new Date(System.currentTimeMillis()), "yyyyMMdd");
        stringBuilder.append(time);
        String keyCode = CipherUtils.md5(stringBuilder.toString());
        String sign = CryptAES.AES_Encrypt(keyCode, loginEntity.mobile);
        loginEntity.mobile = phoneCode;
        presenter.loadSendMsg(loginEntity, sign);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.text_send_phone_again:
                requestSendMsgAgain();
                break;
            case R.id.bt_identify_nextstep:
                requestIdentifyCode();
                break;

        }
    }

    @Override
    public void showIdentifyCodeView(LoginEntity entity) {
        view_error_message.setError(entity.message);
        if (entity != null && !TextUtils.isEmpty(entity.valid_token)) {
            //TODO 重设登录密码页
            entity.mobile = phoneCode;
            Intent intent = new Intent(this, ResetPWActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable("loginEntity", entity);
            intent.putExtras(bundle);
            startActivity(intent);
        }
    }

    @Override
    public void showErrorData(NetworkManager.ResultCode resultCode, String msg) {
        view_error_message.showErrorMsg(msg);
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showSendMsgAgainView(final LoginEntity entity) {
        if (!TextUtils.isEmpty(entity.message)) {
            view_error_message.showErrorMsg(entity.message);
            second = 60;
            handler.sendEmptyMessageDelayed(99999, 1000);
        }
    }
}
